from django.contrib import auth
from rest_framework import status, viewsets
from rest_framework.decorators import api_view, permission_classes, action
from rest_framework.response import Response

from sqtp.models import Request, Config, Case, Step, Project, Environment, User
from sqtp.permissions import IsOwnerOrRedeOnly
from sqtp.serializers import RequestSerializer, ConfigSerializer, CaseSerializer, StepSerializer, ProjectSerializer, \
    EnvironmentSerializer, UserSerializer, RegisterSerializer, LoginSerializer

''''
可参考，但回滚的时候不小心改了代码
'''
# class RequestList(ListCreateAPIView):
#     queryset = Request.objects.all()
#     serializer_class = RequestSerializer
#
#
# class RequestDetail(RetrieveUpdateDestroyAPIView):
#     queryset = Request.objects.all()
#     serializer_class = RequestSerializer


class RequestViewSet(viewsets.ModelViewSet):
    queryset = Request.objects.all()
    serializer_class = RequestSerializer


class ConfigViewSet(viewsets.ModelViewSet):
    queryset = Config.objects.all()
    serializer_class = ConfigSerializer


'''
用户不会作为序列化参数入参的
'''


class CaseViewSet(viewsets.ModelViewSet):
    queryset = Case.objects.all()
    serializer_class = CaseSerializer
    '''
    在执行 POST 创建数据时额外传一个 created_by 字段的值,字段必须得有哈
    '''

    def perform_create(self, serializer):
        serializer.save(create_by=self.request.user)

    def perform_update(self, serializer):
        serializer.save(update_by=self.request.user)

    '''
    methods=['GET'] → 这个接口只接受 GET 请求
    detail=True → URL 会带主键（pk），作用对象是单个资源（比如单个 Case）
    url_path='run' → 在 URL 里显示成 /run
    url_name='run_case' → 反向解析 URL 时用的名字
    '''
    @action(methods=['GET'], detail=True, url_path='run', url_name='run_case')
    # 完整的url等于/cases/<int:case_id>/run
    def run_case(self, request, pk):
        # 获取序列化器
        case = Case.objects.get(pk=pk)  # 根据ID获取当前用例
        serializer = self.get_serializer(instance=case)
        serializer.to_json_file()
        return Response(data={'msg': 'success', 'retcode': 200})


class StepViewSet(viewsets.ModelViewSet):
    queryset = Step.objects.all()
    serializer_class = StepSerializer


# # Create your views here.
# @api_view(['GET', 'POST'])
# def request_list(request):
#     if request.method == "GET":
#         serializer = RequestSerializer(instance=Request.objects.all(), many=True)
#         return Response(serializer.data)
#     if request.method == "POST":
#         serializer = RequestSerializer(data=request.data)
#         if serializer.is_valid():
#             serializer.save()
#             return Response(serializer.data, status=status.HTTP_201_CREATED)
#         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#
#
# @api_view(['GET', "PUT", "DELETE"])
# def request_detail(request, pk):
#     try:
#         data = Request.objects.get(id=pk)
#         serializer = RequestSerializer(data)
#     except Exception as e:
#         return Response(status=status.HTTP_404_NOT_FOUND)
#
#     if request.method == "GET":
#         serializer = RequestSerializer(instance=data)
#         return Response(serializer.data)
#     elif request.method == "PUT":
#         serializer = RequestSerializer(instance=data, data=request.data)
#         if serializer.is_valid():
#             serializer.save()
#             return Response(serializer.data, status=status.HTTP_200_OK)
#         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#     elif request.method == "DELETE":
#         data.delete()
#         return Response(status=status.HTTP_204_NO_CONTENT)

class ProjectViewSet(viewsets.ModelViewSet):
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer
    # 权限
    # authentication_classes = (SessionAuthentication, BasicAuthentication)
    permission_classes = [IsOwnerOrRedeOnly]


class EnvironmentViewSet(viewsets.ModelViewSet):
    queryset = Environment.objects.all()
    serializer_class = EnvironmentSerializer


@api_view(['GET'])
def user_list(request):
    queryset = User.objects.all()
    serializer = UserSerializer(queryset, many=True)
    return Response(serializer.data)


@api_view(['GET'])
def user_detail(request, pk):
    try:
        queryset = User.objects.get(pk=pk)
    except Exception as e:
        return Response(status=status.HTTP_404_NOT_FOUND)
    serializer = UserSerializer(queryset)
    return Response(serializer.data)


@api_view(['POST'])
@permission_classes([])
def register(request):
    serializer = RegisterSerializer(data=request.data)
    if serializer.is_valid():
        user = serializer.register()
        # 完成用户登录状态设置
        auth.login(request, user)
        return Response(
            status=status.HTTP_201_CREATED,
            data={
                'msg': '用户注册成功',
                'is_admin': user.is_superuser,
                'retcode': status.HTTP_201_CREATED
            }
        )
    return Response(
        data={
            'msg': 'error',
            'retcode': status.HTTP_400_BAD_REQUEST,
            'error': serializer.errors
        },
        status=status.HTTP_400_BAD_REQUEST
    )


# 登录
@api_view(['POST'])
@permission_classes([])
def login(request):
    serializer = LoginSerializer(data=request.data)
    user = serializer.validate(request.data)
    if user:
        auth.login(request, user)
        return Response(
            status=status.HTTP_302_FOUND,
            data={
                'msg': '用户登录成功',
                'retcode': status.HTTP_302_FOUND,
                'to': 'index.html'
            }
        )
    return Response(
        status=status.HTTP_400_BAD_REQUEST,
        data={
            'msg': 'error',
            'retcode': status.HTTP_400_BAD_REQUEST,
            'error': serializer.errors
        }
    )


# 登出
@api_view(['GET'])
@permission_classes([])
def logout(request):
    if request.user.is_authenticated:
        auth.logout(request)  # 清除登录信息
        print("清楚用户信息")
    return Response(
        status=status.HTTP_302_FOUND,
        data={
            'msg': '用户退出登录成功',
            'retcode': status.HTTP_302_FOUND,
            'to': 'login.html'
        }
    )


# 获取当前用户信息视图
@api_view(['GET'])
@permission_classes([])
def current_user(request):
    if request.user.is_authenticated:
        serializer = UserSerializer(request.user)
        return Response(data=serializer.data)
    else:
        return Response(
            status=status.HTTP_403_FORBIDDEN,
            data={
                'msg': '您未登录',
                'to': 'login.html',
                'retcode': status.HTTP_403_FORBIDDEN
            }
        )
